
# import sys,os
# import importlib
#
# spec = importlib.util.spec_from_file_location("module.name", "expert/fish.py")
# module = importlib.util.module_from_spec(spec)
# sys.modules["module.name"] = module
# spec.loader.exec_module(module)
#
# # 从模块中获取类
# cls = getattr(module, 'fish')
# print(f"Successfully imported {'fish'} from {'expert'}")
# res = cls()

# import pandas as pd
# data = pd.read_csv("data/data_example.csv")
# analysis_results = []
# recommendations = []
# print(data.loc[:, 'sum'])
#
# result = f"Analyzing row sum: "
# recommendation = f"Recommendation for row sum: "
#
# # 示例参数：溶解氧 (DO)
# if float(data['sum'][7]) < 5:
#     result += "Low dissolved oxygen. "
#     recommendation += "Increase aeration. "
# elif float(data['sum'][7]) > 9:
#     result += "High dissolved oxygen. "
#     recommendation += "Decrease aeration. "
# else:
#     result += "Dissolved oxygen level is normal. "
#
# # 示例参数：pH值
# if float(data['sum'][8]) < 6.5:
#     result += "Low pH. "
#     recommendation += "Add alkaline substances. "
# elif float(data['sum'][8]) > 8.5:
#     result += "High pH. "
#     recommendation += "Add acidic substances. "
# else:
#     result += "pH level is normal. "
#
# # 示例参数：温度
# if float(data['sum'][9]) < 20:
#     result += "Low temperature. "
#     recommendation += "Increase water temperature. "
# elif float(data['sum'][9]) > 30:
#     result += "High temperature. "
#     recommendation += "Decrease water temperature. "
# else:
#     result += "Temperature level is normal. "
#
# analysis_results.append(result)
# recommendations.append(recommendation)
#
# for analysis in analysis_results:
#     # self.textBrowser.append(analysis + "<br>")
#     print(analysis)
# for recommendation in recommendations:
#     # self.textBrowser.append(recommendation + "<br>")
#     print(recommendation)

# import pandas as pd
# data = pd.read_csv("data/data_example.csv")
# analysis_results = []
# recommendations = []
# n = 0
# for column_name, column_data in data.iteritems():
#     if n>0:
#
#         result = f"Analyzing {column_name}: "
#         recommendation = f"Recommendation for camera {column_name}: "
#
#         # 示例参数：溶解氧 (DO)
#         if float(column_data[7]) < 5:
#             result += "Low dissolved oxygen. "
#             recommendation += "Increase aeration. "
#         elif float(column_data[7]) > 9:
#             result += "High dissolved oxygen. "
#             recommendation += "Decrease aeration. "
#         else:
#             result += "Dissolved oxygen level is normal. "
#
#         # 示例参数：pH值
#         if float(column_data[8]) < 6.5:
#             result += "Low pH. "
#             recommendation += "Add alkaline substances. "
#         elif float(column_data[8]) > 8.5:
#             result += "High pH. "
#             recommendation += "Add acidic substances. "
#         else:
#             result += "pH level is normal. "
#
#         # 示例参数：温度
#         if float(column_data[9]) < 20:
#             result += "Low temperature. "
#             recommendation += "Increase water temperature. "
#         elif float(column_data[9]) > 30:
#             result += "High temperature. "
#             recommendation += "Decrease water temperature. "
#         else:
#             result += "Temperature level is normal. "
#
#         analysis_results.append(result)
#         recommendations.append(recommendation)
#     n+=1
#     continue
# for analysis in analysis_results:
#     print(analysis)
# for recommendation in recommendations:
#     print(recommendation)

# import pandas as pd
# import numpy as np
# data = pd.read_csv("data/data_example.csv")
# dataset = np.array(data)
# print(dataset)
#
#
# import numpy as np
# a = np.array([[1,2,3]])
# b = np.array([[2,1,4]])
# c = np.concatenate((a, b), axis=0)
# print(c)


# print([0 for _ in range(3)])

import socket
import cv2
import numpy as np
import os
import threading
import time

clients = {}
save_images = {}

def handle_client(conn, addr):
    print(f"客户端 {addr} 已连接.")
    client_dir = f'received_images/{addr[0]}_{addr[1]}'
    os.makedirs(client_dir, exist_ok=True)
    save_interval = 10  # 保存间隔时间（秒）
    last_save_time = time.time()

    clients[addr] = conn
    save_images[addr] = True  # 默认保存图像

    try:
        while True:
            length = recvall(conn, 16)  # 接收数据长度
            if not length:
                break
            string_data = recvall(conn, int(length))
            data = np.frombuffer(string_data, dtype='uint8')

            frame = cv2.imdecode(data, cv2.IMREAD_COLOR)
            cv2.imshow(f'服务器接收到的图像 - {addr}', frame)

            # 每隔10秒保存一次图像
            current_time = time.time()
            if current_time - last_save_time >= save_interval and save_images[addr]:
                cv2.imshow(frame)
                last_save_time = current_time

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    except ConnectionResetError as e:
        print(f"连接中断: {e}")
    finally:
        conn.close()
        del clients[addr]
        del save_images[addr]

    cv2.destroyAllWindows()

def recvall(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf:
            return None
        buf += newbuf
        count -= len(newbuf)
    return buf

def save_image(frame, client_dir):
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"received_image_{timestamp}.jpg"
    file_path = os.path.join(client_dir, filename)
    cv2.imwrite(file_path, frame)
    print(f"保存图像成功: {file_path}")

def server_program():
    host = '0.0.0.0'
    port = 5050

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)

    print(f"服务器已启动，在 {host}:{port} 监听...")

    threading.Thread(target=control_panel).start()

    while True:
        conn, addr = server_socket.accept()
        print(conn)
        threading.Thread(target=handle_client, args=(conn, addr)).start()

def control_panel():
    while True:
        print("\n当前连接的客户端:")
        for i, addr in enumerate(clients.keys()):
            print(f"{i + 1}. {addr}")

        cmd = input("输入客户端编号来切换保存状态，或输入'all'来切换所有客户端，或输入'exit'退出控制面板: ")

        if cmd == 'exit':
            break
        elif cmd == 'all':
            new_state = not all(save_images.values())
            for addr in save_images:
                save_images[addr] = new_state
            state_str = "保存" if new_state else "停止保存"
            print(f"已为所有客户端切换到 {state_str} 状态.")
        else:
            try:
                index = int(cmd) - 1
                addr = list(clients.keys())[index]
                save_images[addr] = not save_images[addr]
                state_str = "保存" if save_images[addr] else "停止保存"
                print(f"已为客户端 {addr} 切换到 {state_str} 状态.")
            except (ValueError, IndexError):
                print("无效的输入，请重试.")

if __name__ == '__main__':
    server_program()